package com.ruoyi.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SealJur;
import com.ruoyi.system.service.*;
import com.ruoyi.web.bean.ESSPdfPage;
import com.ruoyi.web.bean.VerifyResult;
import com.ruoyi.web.dto.SealDto;
import com.ruoyi.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.common.utils.StringUtils.isNull;
import static com.ruoyi.common.utils.file.FileUtils.File2byte;
import static com.ruoyi.web.util.pdf.PdfUtils.convertCoordinate;

@Controller
@RequestMapping(value="/")
public class MainController {
    @Resource
    private ISealJurService sealJurService;
    @Autowired
    private FileService fileService;
    @Autowired
    private CQYCSignService signService;
    @Autowired
    private SealService sealService;
    @Autowired
    private IBusinessSysService businessSysService;
    @Autowired
    private IPersonService personService;
    @Autowired
    private IDockingErrService dockingErrService;
    @Resource
    private IPdfTokenService pdfTokenService;


    /**
     * 根据单位ID和印章类型返回印章ID列表
     * @param data 参数 unitId sealType
     * @return 印章ID 印章名臣列表
     */
//    @RequestMapping(value ="/getSealByUidAndType")
//    @ResponseBody
//    public String getSealByUidAndType(String data) {
//        //取出参数
//        JSONObject dataJs = JSONObject.parseObject(data);
//        //单位ID
//        String unitId = dataJs.getString("unitId");
//        //印章类型
//        String sealType = dataJs.getString("sealType");
//        //根据单位和部门查找印章列表
//        List<SealDto> sealList = sealService.getSealByUidAndType(unitId,sealType);
//        JSONArray jsonArray = new JSONArray();
//        for (SealDto sealDto :sealList){
//            JSONObject jsonObject = new JSONObject();
//            String sealName = sealDto.getSealName();
//            String sealId = sealDto.getSealId();
//            jsonObject.put("sealName",sealName);
//            jsonObject.put("sealId",sealId);
//            jsonArray.add(jsonObject);
//        }
//        return jsonArray.toJSONString();
//    }
    /**
     * 根据单位ID返回印章ID列表
     * @param data 参数 unitId
     * @return 印章ID 印章名臣列表
     */
    @RequestMapping(value ="/getSealByUid")
    @ResponseBody
    public String getSealByUid(String data) {
        //取出参数
        JSONObject dataJs = JSONObject.parseObject(data);
        //单位ID
        String unitId = dataJs.getString("unitId");
        //根据单位和部门查找印章列表
        List<SealDto> sealList = sealService.getSealByUnitId(unitId);
        JSONArray jsonArray = new JSONArray();
        for (SealDto sealDto :sealList){
            JSONObject jsonObject = new JSONObject();
            String sealName = sealDto.getSealName();
            String sealId = sealDto.getSealId();
            String sealTypeId = sealDto.getSeal_type();
            jsonObject.put("sealName",sealName);
            jsonObject.put("sealId",sealId);
            jsonObject.put("sealTypeId",sealTypeId);
            jsonArray.add(jsonObject);
        }
        return jsonArray.toJSONString();
    }

    /**
     * 根据单位ID返回印章ID列表
     * @param data 参数 unitId
     * @return 印章ID 印章名臣列表
     */
    @RequestMapping(value ="/getSealByUserId")
    @ResponseBody
    public String getSealByUserid(String data,HttpServletRequest request){
        data = complementParam(data,request);
        JSONObject result = new JSONObject();
        //首先确认参数
        JSONObject dataJs = null;
        try{
            dataJs = JSONObject.parseObject(data);
        }catch (Exception e){
            result.put("code","0001");
            result.put("msg","参数格式异常");
            return result.toJSONString();
        }
        //单位ID
        String userId = dataJs.getString("signUser");
        //单位ID
        String sysId = dataJs.getString("businessSys");
        //根据业务系统和人员查找授权列表
        List<SealJur> sealJurs = sealJurService.selectAllSealJurByUserId(userId,sysId);

        List<SealDto> sealList = new ArrayList<>();
        for (SealJur s:sealJurs) {
            SealDto sealDto = sealService.findSealById(s.getSealId());
            if(!isNull(sealDto)){
                sealList.add(sealDto);
            }
        }
        if (sealList.size() == 0){
            result.put("code","w0002");
            result.put("msg","用户ID错误");
            return result.toJSONString();
        }
        JSONArray jsonArray = new JSONArray();
        for (SealDto sealDto: sealList) {
            JSONObject jo = new JSONObject();
            jo.put("sealId",sealDto.getSealId());
            jo.put("sealName",sealDto.getSealName());
            jo.put("sealImg",sealDto.getSeal_img());
            jsonArray.add(jo);
        }
        result.put("code","w0000");
        result.put("msg","成功");
        result.put("data",jsonArray);
        return result.toJSONString();
    }

    /**
     * 根据单位ID返回印章ID列表
     * @param data 参数 unitId
     * @return 印章ID 印章名臣列表
     */
    @RequestMapping(value ="/getSealByType")
    @ResponseBody
    public String getSealByType(String data) {
        //取出参数
        JSONObject dataJs = JSONObject.parseObject(data);
        //单位ID
        String sealType = dataJs.getString("sealTypeId");
        //根据类型印章列表
        List<SealDto> sealList = sealService.getSealBySealType(sealType);
        JSONArray jsonArray = new JSONArray();
        for (SealDto sealDto :sealList){
            JSONObject jsonObject = new JSONObject();
            String sealName = sealDto.getSealName();
            String sealId = sealDto.getSealId();
            String sealTypeId = sealDto.getSeal_type();
            jsonObject.put("sealName",sealName);
            jsonObject.put("sealId",sealId);
            jsonObject.put("sealTypeId",sealTypeId);
            jsonArray.add(jsonObject);
        }
        return jsonArray.toJSONString();
    }
//    /**
//     * 根据userID和印章类型返回印章ID列表,需要去授权表中取值 其中keywords 和sealTypeId 为筛选条件
//     * @param data 参数 userId businessSys keywords  sealTypeId
//     * @return 印章ID 印章名臣列表
//     */
//    @RequestMapping(value ="/getSealByUserId")
//    @ResponseBody
//    public String getSealByUserId(String data) {
//        //取出参数
//        JSONObject dataJs = JSONObject.parseObject(data);
//        //单位ID
//        String userId = dataJs.getString("userId");
//        String businessSys = dataJs.getString("businessSys");
//        String keywords = "";
//        if (dataJs.containsKey("keywords")){
//            keywords = dataJs.getString("keywords");
//            if (keywords == null ){
//                keywords ="";
//            }
//        }
//        String sealTypeId = "";
//        if (dataJs.containsKey("sealTypeId")){
//            sealTypeId = dataJs.getString("sealTypeId");
//            if (sealTypeId == null || "".equals(sealTypeId)){
//                sealTypeId ="ESS002ESS003";
//            }
//        }
//        //根据单位和部门查找印章列表
//        List<SealDto> sealList = sealService.getSealByUserId(businessSys,userId);
//        JSONArray jsonArray = new JSONArray();
//        for (SealDto sealDto :sealList){
//            if (sealDto.getSealName().contains(keywords)){
//                if (sealTypeId.contains(sealDto.getSeal_type())){
//                    JSONObject jsonObject = new JSONObject();
//                    String sealName = sealDto.getSealName();
//                    String sealId = sealDto.getSealId();
//                    String TypeId = sealDto.getSeal_type();
//                    jsonObject.put("sealName",sealName);
//                    jsonObject.put("sealId",sealId);
//                    jsonObject.put("sealTypeId",TypeId);
//                    jsonArray.add(jsonObject);
//                }
//            }
//        }
//        return jsonArray.toJSONString();
//    }

    /**
     * 根据单位ID和用户ID返回印章ID列表
     * @param data 参数 userId  unitId
     * @return 印章ID 印章名臣列表
     */
    @RequestMapping(value ="/getSealByUserIdAndUnitId")
    @ResponseBody
    public String getSealByUserIdAndUnitId(String data) {
        //取出参数
        JSONObject dataJs = JSONObject.parseObject(data);
        //单位ID
        String userId = dataJs.getString("userId");
        String unitId = dataJs.getString("unitId");
        String businessSys = dataJs.getString("businessSys");
        //根据单位和部门查找印章列表
        List<SealDto> sealList = sealService.getSealByUserIdAndUnitId(businessSys,userId,unitId);
        JSONArray jsonArray = new JSONArray();
        for (SealDto sealDto :sealList){
            JSONObject jsonObject = new JSONObject();
            String sealName = sealDto.getSealName();
            String sealId = sealDto.getSealId();
            String sealTypeId = sealDto.getSeal_type();
            jsonObject.put("sealName",sealName);
            jsonObject.put("sealId",sealId);
            jsonObject.put("sealTypeId",sealTypeId);
            jsonArray.add(jsonObject);
        }
        return jsonArray.toJSONString();
    }
//
//    @RequestMapping(value ="/error")
//    public void error(HttpServletResponse response){
//        try {
//            response.sendRedirect("http://www.baidu.com");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * PDF文档验章接口，图形
     */
    @RequestMapping(value ="/verifyAndShow")
    public ModelAndView show(String data) {
        ModelAndView modelAndView = new ModelAndView();
//        //首先确认参数
        JSONObject dataJs = JSONObject.parseObject(data);
        String documentCode = dataJs.getString("documentCode");
        String type = dataJs.getString("type");
        //查找文档
        File pdfFile = fileService.downloadDocumentFile(documentCode,"pdf");
        if (pdfFile==null){
            modelAndView.addObject("msg","PDF文件不存在");
            modelAndView.setViewName("error");
            return modelAndView;
        }
        //处理PDF
        List<ESSPdfPage> pdfImagesList = fileService.splitPDFToImages(pdfFile);
        modelAndView.addObject("pdfImagesList",pdfImagesList);
        //验证PDF内印章完整性
        if ("1".equals(type)){
            //返回结果
            modelAndView.setViewName("show1");
        }else if ("2".equals(type)){
            List<VerifyResult> verifyResultList =  signService.verifyPdfSign(File2byte(pdfFile));
            modelAndView.addObject("verifyResultList",verifyResultList);
            //返回结果
            modelAndView.setViewName("show");
        }
        return modelAndView;
    }
//    /**
//     * 根据参数生成数据token
//     * @param data
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping(value ="/getSignToken")
//    public String getSignToken(String data, HttpServletRequest request) {
//        data = complementParam(data,request);
//        //存储参数
//    }
    /**
     * 拖拽签章入口
     * @param modelAndView
     * @return 返回PDF展示页面
     * @throws Exception
     */
    @RequestMapping(value ="/move")
    public ModelAndView dPdf(ModelAndView modelAndView,String token) {
        boolean checkResult = pdfTokenService.checkToken(token);
        if (checkResult){
            //返回结果
            modelAndView.setViewName("addSeal");
            modelAndView.addObject("token",token);
        }else{
            modelAndView.setViewName("/error/error");
            modelAndView.addObject("msg","token已失效");
        }
        return modelAndView;
    }
    /**
     * 对接收的参数做一次补全，目的是支持两种参数形式
     * Content-Type: application/x-www-form-urlencoded  参数正文
     * Content-Type: application/json 文本正文
     * @return 参数
     */
    public String complementParam(String data,HttpServletRequest request){
        if (data ==null){
            StringBuilder data1 = new StringBuilder();
            String line ;
            BufferedReader reader ;
            try {
                reader = request.getReader();
                while (null != (line = reader.readLine())) {
                    data1.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            data = data1.toString();
        }
        return data;
    }
}
